<?php
namespace app\controllers\api\account;

use fate\http\Request;
use app\models\User;
use app\libs\Uploader;
use app\libs\LibUser;

class EditavatarController extends \app\controllers\ForceLoginPure {
    public function run() {
        $req = Request::getInstance();

        $uid = LibUser::getLoginUid();
        $avatar = $req->getParameter('avatar');

        if(!$avatar) {
            $this->ajaxReturn(null, 300002);
            exit;
        }

        // 保存头图
        $subdir = substr((string)$uid, 0, 1);
        $uploader = new Uploader();
        $uploader->setConfigs([
            'randomName' => false,
            'saveName' => (string)$uid,
            'rotatePattern' => '',
            'basePath' => './upload/avatar/' . $subdir
        ]);
        $uploader->saveBase64Image($avatar);
        $avatar = $uploader->getFirstUploadedFile();

        if('' === $avatar) {
            $this->ajaxReturn(null, 300003);
            exit;
        }

        // and prefix
        $avatar = '/upload/avatar/' . $subdir . $avatar;

        (new User())->update($uid, ['avatar' => $avatar]);

        $this->ajaxReturn([
            'avatar' => $avatar
        ]);
    }
}
